package com.http.controller;

import com.http.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

/**
 * @author zc
 * @version 1.0
 * @date 2021/9/2 14:36
 */
@RestController
public class TestController {

    @RequestMapping("/doGetControllerOne")
    public String doGetControllerOne(){
        return "123456";
    }


    @RequestMapping("/doGetControllerTwo")
    public String doGetControllerTwo(String name,String age){

        return "没想到["+name+"]都"+age+"岁了！";
    }

    @RequestMapping(value ="/doPostControllerOne",method = RequestMethod.POST)
    public String doPostControllerOne(){
        return "这个post请求没有任何参数！";
    }

    @RequestMapping(value ="/doPostControllerFour",method = RequestMethod.POST)
    public String doPostControllerFour(String name,Integer age){
        return "["+ name +"]居然才["+age+"]岁！！！";
    }

    @RequestMapping(value = "/doPostControllerTwo",method = RequestMethod.POST)
    public String doPostControllerTwo(@RequestBody User user){
        return user.toString();
    }

    @RequestMapping(value = "/doPostControllerThree",method = RequestMethod.POST)
    public String doPostControllerThree(@RequestBody User user,Integer flag ,String meaning){
        return user.toString()+"\n"+flag + ">>>"+meaning;
    }

    @PostMapping(value="/file")
    public String fileControllerTest(@RequestParam("name") String name,
                                     @RequestParam("age") Integer age,
                                     @RequestParam("files")List<MultipartFile> multipartFiles) throws UnsupportedEncodingException {

        StringBuilder sb = new StringBuilder(64);
        // 防止中文乱码
        sb.append("\n");
        sb.append("name=").append(name)
                .append("\tage=").append(age);
        String fileName;
        for (MultipartFile file : multipartFiles) {
            sb.append("\n文件信息:\n");
            fileName = file.getOriginalFilename();
            if (fileName == null) {
                continue;
            }
            // 防止中文乱码
            // 在传文件时，将文件名URLEncode，然后在这里获取文件名时，URLDecode。就能避免乱码问题。
            fileName = URLDecoder.decode(fileName, "utf-8");
            sb.append("\t文件名: ").append(fileName);
            sb.append("\t文件大小: ").append(file.getSize() * 1.0 / 1024).append("KB");
            sb.append("\tContentType: ").append(file.getContentType());
            sb.append("\n");
        }
        return  sb.toString();
    }
}
